#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
台球桌数据模型
"""

from database import db
from datetime import datetime

class BilliardTable(db.Model):
    __tablename__ = 'billiard_tables'
    
    id = db.Column(db.Integer, primary_key=True)
    table_no = db.Column(db.String(20), unique=True, nullable=False, comment='台桌编号')
    table_name = db.Column(db.String(100), nullable=False, comment='台桌名称')
    
    # 台桌信息
    table_type = db.Column(db.String(50), nullable=False, comment='台桌类型：nine_ball九球桌，snooker斯诺克桌，chinese_eight中式八球')
    size = db.Column(db.String(20), nullable=True, comment='台桌尺寸')
    brand = db.Column(db.String(100), nullable=True, comment='台桌品牌')
    
    # 位置信息
    area = db.Column(db.String(50), nullable=True, comment='区域位置')
    floor = db.Column(db.Integer, nullable=True, comment='楼层')
    position = db.Column(db.String(100), nullable=True, comment='具体位置描述')
    
    # 价格信息
    hourly_rate = db.Column(db.DECIMAL(10, 2), nullable=False, comment='小时费率')
    member_rate = db.Column(db.DECIMAL(10, 2), nullable=True, comment='会员费率')
    peak_rate = db.Column(db.DECIMAL(10, 2), nullable=True, comment='高峰费率')
    
    # 状态信息
    status = db.Column(db.String(20), default='available', comment='状态：available可用，occupied占用中，maintenance维护中，disabled已禁用')
    is_premium = db.Column(db.Boolean, default=False, comment='是否VIP台桌')
    
    # 当前使用信息
    current_user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, comment='当前使用用户')
    current_order_id = db.Column(db.Integer, nullable=True, comment='当前订单ID')  # 移除外键约束避免循环依赖
    occupied_since = db.Column(db.DateTime, nullable=True, comment='占用开始时间')
    estimated_end_time = db.Column(db.DateTime, nullable=True, comment='预计结束时间')
    
    # 设备信息
    has_lighting = db.Column(db.Boolean, default=True, comment='是否有照明')
    has_scoreboard = db.Column(db.Boolean, default=False, comment='是否有计分牌')
    qr_code = db.Column(db.String(500), nullable=True, comment='二维码地址')
    
    # 系统字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    last_maintenance = db.Column(db.DateTime, nullable=True, comment='最后维护时间')
    remark = db.Column(db.Text, nullable=True, comment='备注')
    
    # 关联关系
    orders = db.relationship('Order', backref='table', lazy='dynamic', foreign_keys='Order.table_id')
    current_user = db.relationship('User', foreign_keys=[current_user_id])
    # current_order 关系通过手动查询实现，避免循环依赖
    
    def to_dict(self):
        return {
            'id': self.id,
            'table_no': self.table_no,
            'table_name': self.table_name,
            'table_type': self.table_type,
            'size': self.size,
            'brand': self.brand,
            'area': self.area,
            'floor': self.floor,
            'position': self.position,
            'hourly_rate': float(self.hourly_rate),
            'member_rate': float(self.member_rate) if self.member_rate else None,
            'peak_rate': float(self.peak_rate) if self.peak_rate else None,
            'status': self.status,
            'is_premium': self.is_premium,
            'current_user_id': self.current_user_id,
            'current_order_id': self.current_order_id,
            'occupied_since': self.occupied_since.isoformat() if self.occupied_since else None,
            'estimated_end_time': self.estimated_end_time.isoformat() if self.estimated_end_time else None,
            'has_lighting': self.has_lighting,
            'has_scoreboard': self.has_scoreboard,
            'qr_code': self.qr_code,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'last_maintenance': self.last_maintenance.isoformat() if self.last_maintenance else None,
            'remark': self.remark,
            'current_user': self.current_user.to_dict() if self.current_user else None
        }
    
    def is_available(self):
        """检查台桌是否可用"""
        return self.status == 'available'
    
    def get_current_order(self):
        """获取当前订单"""
        if not self.current_order_id:
            return None
        from models.order import Order
        return Order.query.get(self.current_order_id)
    
    def __repr__(self):
        return f'<BilliardTable {self.table_no}>'